package com.telecom.sxint.app.api.controller.UccpMessageController;

import cn.hutool.core.util.StrUtil;
import cn.zjtele.pubinfo.common.http.response.ResponseData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.telecom.sxint.app.core.domain.entity.Engineerpojo.App1Engineercertification;
import com.telecom.sxint.app.core.domain.entity.Messagepojo.App1UccpMessage;
import com.telecom.sxint.app.core.domain.entity.Vatinvoicepojo.App1Vatinvoinceprintlog;
import com.telecom.sxint.app.core.service.Messageservice.IApp1UccpMessageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author zhulintao
 * @version 2.0
 * @date 2024/12/9 10:10
 */
@RestController
@RequestMapping("/app1-UccpMessage")
@Tag(name = "导出控制器", description = "信息导出管理")
@RequiredArgsConstructor
public class App1UccpMessageUploadController {
    private final IApp1UccpMessageService iApp1UccpMessageService;
    String getCellValue(Cell cell) {
        if (cell != null) {
            switch (cell.getCellType()) {
                case STRING:
                    return cell.getStringCellValue();
                case NUMERIC:
                    return String.valueOf(cell.getNumericCellValue());
                case BOOLEAN:
                    return String.valueOf(cell.getBooleanCellValue());
                default:
                    return "";
            }
        }
        return "";
    }
    /**
     * 导入文件
     * @param file
     * @return
     */
    @Operation(summary = "导入短信文档录入数据库", description = "返回测试信息表分页")
    @PostMapping("/Fileupload")
    public ResponseData<List<App1UccpMessage>>  handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseData.failed("没有文件","4101");
        }
        String fileName = file.getOriginalFilename();
        if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
            return ResponseData.failed("文件格式错误","4103");
        }
        try (InputStream inputStream = file.getInputStream();
             Workbook workbook = WorkbookFactory.create(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                // 工作表为空，返回错误信息或空列表
                return ResponseData.failed("没有可读取的工作表","4100");
            }
            if(!sheet.getRow(0).getCell(0).getStringCellValue().equals("手机号") ||
                    !sheet.getRow(0).getCell(1).getStringCellValue().equals("发送信息")) {
                return ResponseData.failed("文件格式错误","4103");
            }
            List<App1UccpMessage> app1= new ArrayList<>();
            for (Row row : sheet) {
                if (row.getRowNum() == 0) continue; // Skip header row if present
                if(StrUtil.isBlank(getCellValue(row.getCell(0)))||StrUtil.isBlank(getCellValue(row.getCell(1)))){
                    continue;
                }
                App1UccpMessage log = new App1UccpMessage();
                String phoneNumber=getCellValue(row.getCell(0));
                // 使用 BigDecimal 解析科学记数
                BigDecimal phoneNum = new BigDecimal(phoneNumber);
                log.setPhoneNumber(phoneNum.toString());
                log.setMessageContent(getCellValue(row.getCell(1)));
                log.setStorageTime(LocalDateTime.now());
                String PhoneNumber = log.getPhoneNumber();
                String Content = log.getMessageContent();
                if (PhoneNumber.equals("") && Content.equals("")) {
                    System.out.println("PhoneNumber 和 Content 都为空，跳过当前插入操作");
                } else {
                    // 处理日志和保存操作
                    app1.add(log);
                }
            }
            iApp1UccpMessageService.saveBatch(app1);
            return ResponseData.success(app1);

        } catch (IOException e) {
            return ResponseData.failed("导入失败","4102");
        }
    }

    /**
     * 导出短信excel模板
     * @return
     */
    @Operation(summary = "导出短信信息excel模板", description = "导出位置在D:\\UccpMessage.xlsx")
    @GetMapping("/exportTicketTemplate")
    public ResponseEntity<ByteArrayResource> exportTicketTemplate() {
        try (XSSFWorkbook workbook = new XSSFWorkbook()) {
            // 创建一个空白工作表
            XSSFSheet sheet = workbook.createSheet("Blank Template");

            // 创建标题行
            XSSFRow titleRow = sheet.createRow(0);
            titleRow.createCell(0).setCellValue("手机号");
            titleRow.createCell(1).setCellValue("发送信息");

            // 创建一个示例数据行
            XSSFRow dataRow = sheet.createRow(1); // 第一行数据从索引1开始
            dataRow.createCell(0).setCellValue("11111111");
            dataRow.createCell(1).setCellValue("你好");

            // 将工作簿转换为字节流
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            workbook.write(bos);
            byte[] bytes = bos.toByteArray();
            // 创建Resource对象
            ByteArrayResource resource = new ByteArrayResource(bytes);

            // 设置HTTP响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=UccpMessage.xlsx");

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (Exception e) {
            e.printStackTrace();
            // 处理异常
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}
